package controllers;

import controllers.CRUD.ObjectType;
import models.User;
import play.Play;
import play.db.Model;
import play.exceptions.TemplateNotFoundException;
import play.libs.Crypto;
import play.mvc.Before;
import play.mvc.With;


@With(Secure.class)
@CRUD.For(value = User.class)
public class ChangePassword extends ArcadiaCRUD {

	@Before
    static void setConnectedUser() {
        if(Security.isConnected()) {
            User user = Security.getConnected();
            if (user.arcadiano!=null)
            	renderArgs.put("user", user.arcadiano.nombre);
            else
            	renderArgs.put("user", user.username);
        }
    }

	public static void list(int page, String search, String searchFields, String orderBy, String order) {
		try {
			show(Security.getConnected().id.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void show(String id) throws Exception {
        render();
    }

	public static void changePassword(String id) throws Exception {
    	String oldPassword = params.get("object.oldpassword");
    	String newPassword = params.get("object.newpassword");
    	String confirmPassword = params.get("object.confirmpassword");
    	
    	oldPassword = Crypto.encryptAES(oldPassword, Play.configuration.getProperty("application.privateKey"));
    	
    	User user = Security.getConnected();
    	if(!oldPassword.equals(user.password)) {
    		String message = play.i18n.Messages.get("changepassword.password.wrong");
    		if(oldPassword.equals(""))
    			message = play.i18n.Messages.get("changepassword.oldpassword.required");
    		renderArgs.put("error", message);
    		render(request.controller.replace(".", "/") + "/show.html", null, null);
    	}
    	else if(newPassword.equals("")) {
    		renderArgs.put("error", play.i18n.Messages.get("changepassword.newpassword.required"));
   		 	render(request.controller.replace(".", "/") + "/show.html", null, null);
    	}
    	else if(!newPassword.equals(confirmPassword)) {
    		String message = play.i18n.Messages.get("changepassword.newpasswordNotEqualConfirmpassword");
    		if(confirmPassword.equals(""))
    			message = play.i18n.Messages.get("changepassword.confirmpassword.required");
    		renderArgs.put("error", message);
   		 	render(request.controller.replace(".", "/") + "/show.html", null, null);
    	}
    	
    	user.password = Crypto.encryptAES(newPassword, Play.configuration.getProperty("application.privateKey"));
    	
    	user._save();
    	
    	flash.success(play.i18n.Messages.get("changepassword.success"));
    	redirect("Admin.index");
    }
}
